package org.backend.controller;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.backend.pojo.vo.UserCartVO;
import org.backend.pojo.entity.Cart;
import org.backend.service.CartService;
import org.backend.utils.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

import static org.backend.utils.JwtUtil.setOpenId;

@RestController
@RequestMapping("/cart")
@Slf4j
public class CartController {

    @Autowired
    private CartService cartService;

    @PostMapping("/getUserCart")
    public ApiResponse<List<UserCartVO>> getUserCart(@RequestBody Cart cart, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        cart = setOpenId(cart, token);
        return cartService.getUserCart(cart);
    }

    /**
     * 将商品添加到购物车
     *
     * @param cart
     * @return
     */
    @PostMapping("/add")
    public ApiResponse<String> add(@RequestBody Cart cart, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        cart = setOpenId(cart, token);
        return cartService.add(cart);
    }

    /**
     * 从购物车中删除该商品
     *
     * @param cart
     * @return
     */
    @PostMapping("/remove")
    public ApiResponse<String> remove(@RequestBody Cart cart) {
        return cartService.remove(cart);
    }

    /**
     * 购物车中的商品+1
     *
     * @param cart
     * @return
     */
    @PostMapping("/addProduct")
    public ApiResponse<String> addProduct(@RequestBody Cart cart) {
        return cartService.addProduct(cart);
    }

    /**
     * 购物车中的商品-1
     *
     * @param cart
     * @return
     */
    @PostMapping("/subProduct")
    public ApiResponse<String> subProduct(@RequestBody Cart cart) {
        return cartService.subProduct(cart);
    }

}
